import { commonTablePost } from '@/api/commonPropertypage/index.js';
import { uploadMulti } from '@/api/file';
import { getToken } from '@/utils/auth.js';
import { uploadInvoice } from '@/api/quotaInvoice/index.js';
const bpmParam = {
  action: '',
  destination: '',
  defId: '',
  opinion: '',
  taskIds: '',
  instanceId: '',
  extendConf: {
    nodeId: ''
  },
  nodeUsers: {},
  defKey: '',
  sId: '',
  year: new Date().getFullYear() + '',
  type: '',
  linkPhone: '',
  linkName: ''
};
const ywParam = {
  menuId: '',
  userId: '',
  tableDate: '',
  formGuid: '',
  bodyData: []
};
export default {
  extend(target, source) {
    for (var obj in source) {
      target[obj] = source[obj];
    }
    return target;
  },

  null2str(data) {
    for (const x in data) {
      if (data[x] == null) {
        data[x] = '';
      } else {
        if (Array.isArray(data[x])) {
          data[x] = data[x].map(z => {
            return this.null2str(z);
          });
        }
        if (typeof data[x] === 'object') {
          data[x] = this.null2str(data[x]);
        }
      }
    }
    return data;
  },

  async addCommon(_this, type) {
    if (_this.radio === '' && _this.freeSelectNode && type === 'start') {
      // _this.loadingAll.close();
      _this.$message({
        message: '人工决策不能为空',
        type: 'warning'
      });
    } else {
      if (type === 'start') {
        _this.startLoading = true;
      } else if (type === '') {
        // 暂存新增temporary参数,让后端不校验业务字段
        ywParam.temporary = true;
        _this.timeoutLoading = true;
      }
      this.commonDataDo(_this, type);
      const processedTable = {
        bpmBody: bpmParam,
        ...ywParam
      };
      await this.commonMethodTable(
        this.null2str(processedTable),
        '/dynamicForm/save',
        _this
      );
    }
  },
  async editCommon(_this, type) {
    _this.$refs.commonDialog.dialogVisible = false;
    if (type === 'agree') {
      _this.agreeLoading = true;
    } else if (type === 'reject') {
      _this.rejectLoading = true;
    }
    this.commonDataDo(_this, type);
    const processedTable = {
      bpmBody: bpmParam,
      ...ywParam
    };
    await this.commonMethodTable(
      this.null2str(processedTable),
      '/dynamicForm/save',
      _this
    );
  },
  async abandonment(_this, type) {
    await commonTablePost(
      {
        formGuid: _this.$route.query.formGuid
      },
      '/dynamicForm/reject'
    ).then(res => {
      if (res.success) {
        _this.showSuccess = false;
        setTimeout(() => {
          _this.$refs.showSuccessTree.treego();
        }, 500);
      } else {
        _this.$message({
          message: '废弃失败',
          type: 'warning'
        });
      }
    });
  },
  commonDataDo(_this, type) {
    ywParam.bodyData = [];
    ywParam.menuId = _this.$route.query.menuId;
    ywParam.formGuid = _this.$route.query.formGuid;
    ywParam.tableDate = _this.form.createTime;
    if (_this.$route.query.formGuid === '' || _this.flag === 0) {
      ywParam.bodyData.push({
        tableId: _this.parentTableInfoId,
        data: _this.parentHeaders
      });
    }
    ywParam.bodyData = ywParam.bodyData.concat(_this.bodyData);
    bpmParam.action = type;
    bpmParam.defKey = _this.$route.query.key;
    bpmParam.sId = _this.$route.query.sId;
    bpmParam.destination = _this.radio;

    bpmParam.defId = _this.$route.query.defId;
    bpmParam.taskId = _this.$route.query.taskId;
    if (_this.$route.query.formGuid === '') {
      bpmParam.linkPhone = getToken('username');
      bpmParam.linkName = getToken('xcNickName');
    } else {
      bpmParam.linkPhone = _this.form.tel;
      bpmParam.linkName = _this.form.contacts;
    }

    if (_this.$route.query.flag === 0) {
      ywParam.userId = getToken('xcUserId');
      bpmParam.opinion = '同意';
    } else {
      bpmParam.opinion = _this.$refs.commonDialog.opinion;
    }

    bpmParam.formGuid = _this.$route.query.formGuid;
    if (_this.freeSelectNode && type !== '') {
      bpmParam.nodeUsers[_this.radio] = [];
      _this.nextUser.map(o => {
        bpmParam.nodeUsers[_this.radio].push({
          id: o.split(' ')[0],
          name: o.split(' ')[1],
          type: o.split(' ')[2]
        });
      });
    }
  },
  async commonMethodTable(data, url, _this) {
    await commonTablePost(data, url).then(async res => {
      if (res.success) {
        if (_this.files.length) {
          const fileUploadArr = [];
          _this.files.forEach(async item => {
            if (
              item.file.length &&
              !Object.keys(item.file[0]).includes('voiceObj')
            ) {
              const obj = {
                files: item.file,
                type: _this.$route.query.fileType,
                guid: res.data.formGuid,
                description: item.description
              };
              fileUploadArr.push(this.fileUpload(obj, {}));
            } else if (
              item.file.length &&
              Object.keys(item.file[0]).includes('voiceObj')
            ) {
              // let voiceFiles=[]
              // 发票校验
              const voiceData = new FormData();
              item.file.forEach(it => {
                voiceData.append('files', it.file);
              });
              // console.log(2,voiceFiles);

              voiceData.append('tableId', item.description);
              voiceData.append('formGuid', res.data.formGuid);
              voiceData.append('type', item.file[0].type);
              await uploadInvoice(voiceData).then(res => {
                if (res.success) {
                  _this.$message({
                    message: res.message,
                    type: 'success'
                  });
                } else {
                  _this.$message({
                    message: res.message,
                    type: 'warning'
                  });
                }
              });
            }
          });
          await Promise.all(fileUploadArr).then(res => {
            const resFalse = res.some(item => !item.success);
            if (!resFalse) {
              _this.showSuccess = false;
              setTimeout(() => {
                _this.$refs.showSuccessTree.treego();
              }, 500);
            } else {
              const resData = res.find(item => !item.success);
              _this.$message({
                message: resData.message + ',' + resData.detail,
                type: 'warning'
              });
            }
          });
        } else {
          _this.showSuccess = false;
          setTimeout(() => {
            _this.$refs.showSuccessTree.treego();
          }, 500);
        }
      } else {
        _this.$message({
          message: res.message + ',' + res.detail,
          type: 'warning'
        });
      }
    });
  },
  fileUpload(obj, { formRequestData, additionParams }) {
    return new Promise((resolve, reject) => {
      const upfileRequest = new FormData();
      for (let i = 0; i < obj.files.length; i++) {
        upfileRequest.append('files', obj.files[i].file);
      }

      if (formRequestData) {
        Object.keys(formRequestData).forEach(key => {
          upfileRequest.append(
            key,
            JSON.stringify(Reflect.get(formRequestData, key))
          );
        });
      }

      if (additionParams) {
        Object.keys(additionParams).forEach(key => {
          upfileRequest.append(key, additionParams[key]);
        });
      }
      obj.type && upfileRequest.append('type', obj.type);
      upfileRequest.append('guid', obj.guid);
      upfileRequest.append('description', obj.description);
      uploadMulti(upfileRequest).then(res => {
        resolve(res);
      });
    });
  }
};
